<template>
  <div class="pagebody">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 代理管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="search-box">

      </div>
      <div class="handle-box">
        <el-button type="primary"
                   icon="el-icon-refresh"
                   @click="handleRefresh">重新加载</el-button>
        <el-button type="primary"
                   icon="el-icon-plus"
                   @click="handleAddNew">新建</el-button>

      </div>
      <el-table :data="tableData"
                v-loading="tableLoading"
                border
                class="table"
                ref="mainTable"
                header-cell-class-name="table-header">

        <!-- <el-table-column prop="id"
                         label="代理ID"
                         align="center"></el-table-column> -->
        <el-table-column prop="name"
                         label="代理名称"
                         align="center"></el-table-column>
        <el-table-column prop="contact"
                         label="姓名"
                         align="center"></el-table-column>
        <el-table-column prop="mobile"
                         label="电话"
                         align="center"></el-table-column>
        <el-table-column prop="address"
                         label="地址"
                         align="center"></el-table-column>
        <el-table-column label="代理数量"
                         width="80"
                         align="center">
          <template slot-scope="props">
            <div>{{props.row.courieres&&props.row.courieres.length?props.row.courieres.length:0}}</div>
          </template>
        </el-table-column>
        <el-table-column label="代理快递详情"
                         min-width="140"
                         align="center">
          <template slot-scope="props">
            <div v-if="props.row.courieres.length>0"
                 class="FlexRow FlexCenter">

              <div v-if="!props.row.close">{{props.row.courieres[0].courierIdName}}
              </div>
              <div v-else
                   class="FlexColHStart">
                <div :key="index"
                     v-for="(item,index) in props.row.courieres">{{index+1}}.{{item.courierIdName}}</div>
              </div>
              <el-button style="margin-left:10px;"
                         v-if="props.row.courieres.length>1"
                         type="primary"
                         icon="el-icon-d-caret"
                         @click="SwitchClose(props)"
                         circle></el-button>
            </div>
            <!-- 
          -->
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="140"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text"
                       icon="el-icon-delete"
                       class="color-red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button type="text"
                       icon="el-icon-s-order"
                       @click="handleDetail(scope.$index, scope.row)">财务明细</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="editIsNewAdd?'新建代理':'编辑代理'"
               v-dialogDrag
               center
               :visible.sync="editVisible"
               width="60%">
      <el-form ref="form"
               :model="form"
               :rules="formRules"
               label-width="120px">

        <el-form-item label="代理名称"
                      prop="name">
          <el-input v-model="form.name"
                    placeholder="请输入代理名称"
                    maxlength="15"
                    show-word-limit
                    clearable
                    class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="姓名"
                      prop="contact">
          <el-input v-model="form.contact"
                    placeholder="请输入姓名"
                    maxlength="15"
                    show-word-limit
                    clearable
                    class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      prop="mobile">
          <el-input v-model="form.mobile"
                    placeholder="请输入电话"
                    maxlength="25"
                    show-word-limit
                    clearable
                    class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="地址"
                      prop="address">
          <el-input v-model="form.address"
                    placeholder="请输入地址"
                    maxlength="100"
                    type="textarea"
                    show-word-limit
                    clearable
                    class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="代理快递详情"
                      v-if="!editIsNewAdd"
                      prop="courieres">
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="formAddDetail">新增代理快递</el-button>
          <el-row type="flex"
                  justify="space-between"
                  v-for="(item,index) in form.courieres"
                  :key="index">
            <el-col :span="3">
              第{{index+1}}项.
            </el-col>
            <el-col :span="14">
              <el-select v-model="item.courierId"
                         style="width:100%"
                         placeholder="选择快递">
                <el-option :label="nitem.name"
                           :value="nitem.id"
                           v-for="(nitem,nindex) in CourierDict"
                           :key="nindex"></el-option>

              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button type="danger"
                         plain
                         icon="el-icon-delete"
                         @click="formDeleteDetail(index)"></el-button>
            </el-col>
          </el-row>

        </el-form-item>

      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="财务明细"
               v-dialogDrag
               center
               :visible.sync="detailVisible"
               width="85%">
      <el-descriptions :column="1"
                       style="margin-bottom: 20px"
                       border>
        <el-descriptions-item label="代理商">
          {{ detailform.agentname }}
        </el-descriptions-item>
      </el-descriptions>
      <div>
        <div>合计:</div>
        <div>
          <ul>
            <li v-for="item in detailUserAccounts"
                :key="item.currencyid">
              {{ item.currencyname }}:<span>充值金额:</span>{{ item.chargeamount }}<span>支出金额:</span>{{ item.consumeamount }}
            </li>
          </ul>
        </div>
      </div>
      <el-table :data="tableDetailData"
                v-loading="tableDetailLoading"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header">
        <el-table-column label="状态"
                         align="center">
          <template slot-scope="scope">
            <div class="CustomTag"
                 :style="{
                                'background-color': typeOption[scope.row.type] ? typeOption[scope.row.type].color : '#909399'
                            }">
              {{ typeOption[scope.row.type] ? typeOption[scope.row.type].label : '无效' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="currencyname"
                         label="币种"
                         align="center"></el-table-column>
        <el-table-column prop="amount"
                         label="金额"
                         align="center"></el-table-column>
        <el-table-column prop="adduser"
                         label="经手人"
                         align="center"></el-table-column>
        <el-table-column prop="addtime"
                         label="时间"
                         align="center"></el-table-column>
        <el-table-column label="充值方式"
                         align="center">
          <template slot-scope="scope">
            <div class="CustomTag"
                 :style="{
                                'background-color': chargeTypeOption[scope.row.paytype]
                                    ? chargeTypeOption[scope.row.paytype].color
                                    : '#909399'
                            }">
              {{ chargeTypeOption[scope.row.paytype] ? chargeTypeOption[scope.row.paytype].label : '订单支付扣款' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单"
                         width="120"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-s-order"
                       @click="handleDetailOrder(scope.$index, scope.row)"
                       v-if="scope.row.ordercode">{{ scope.row.ordercode }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="sizes, total, prev, pager, next"
                       :current-page="detailQuery.index"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       :page-size="detailQuery.pageSize"
                       :total="itemDetailTotal"
                       @current-change="handleDetailPageChange"
                       @size-change="handleDetailPageSizeChange"></el-pagination>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="detailVisible = false">确 定</el-button>

        <el-button type="primary"
                   @click="handleExport">导出</el-button>
      </span>
    </el-dialog>
    <detailDialog :visible.sync="detailOrderVisible"
                  :data="detailOrderForm"
                  :dataType="detailOrderType"> </detailDialog>
  </div>
</template>

<script>
import API from '../../../api/index';//读入restfulAPI
import StringTool from '../../../utils/StringTool'
import JSTool from '../../../utils/JSTool'
import dataTable from './dataTable'
import detailDialog from '../../common/dialog/detailDialog.vue';
export default {
  name: 'courierCannelInTable',
  mixins: [dataTable],
  components: {
    detailDialog
  },
  data () {
    let CheckDigit = (rule, value, callback) => {
      if (!StringTool.DigitNumber(String(value))) {
        return callback(new Error('只能为整数和保留两位小数'));
      }
      if (Number(value) < 0) {
        return callback(new Error('只能为正数'));
      }
      callback();
    };
    let CheckFormDetail = (rule, value, callback) => {

      if (!value || value.length <= 0) {
        return callback(new Error('至少需要一个代理'));
      }
      for (let i = 0; i < value.length; i++) {
        if (value[i].courierId == null) {
          return callback(new Error('代理快递不能为空'));
        }
        for (let j = i + 1; j < value.length; j++) {
          if (value[j].courierId == value[i].courierId) {
            return callback(new Error('代理快递不能重复'));
          }

        }
      }
      callback();
    };
    return {
      searchSet: {
        name: "",

      },
      query: {
        status: 1,
        index: 1,
        pageSize: 10
      },
      editVisible: false,
      editIsNewAdd: false,

      CourierDict: [],
      form: {
        contact: "",
        mobile: "",
        address: "",
        name: "",
      },
      formRules: {
        name: [
          { required: true, message: '参数不能为空', trigger: 'change' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'change' }
        ],
        courieres: [
          { validator: CheckFormDetail, required: true, trigger: 'change' }
        ],
      },
      detailQuery: {
        index: 1,
        pageSize: 10
      },
      detailform: {},
      detailVisible: false,
      tableDetailData: [],
      itemDetailTotal: 0,
      tableDetailLoading: false,
      detailUserAccounts: [],
      typeOption: {
        '-1': { label: '支出', value: '-1', color: '#ffb248' },
        1: { label: '充值', value: '1', color: '#339ca8' }
      },
      chargeTypeOption: {
        1: { label: '银行转帐', value: 1, color: '#ffb248' },
        2: { label: '微信转帐', value: 2, color: '#339ca8' },
        3: { label: '支付宝转帐', value: 3, color: '#eb8146' },
        4: { label: '现金', value: 4, color: '#67C23A' }
      },
      detailOrderVisible: false,
      detailOrderForm: {
        id: '',
        code: '',
        agentid: '',
        agentname: '',
        agentprice: '',
        localagentprice: '',
        price: '',
        freightprice: '',
        appusercode: '',
        username: '',
        userPay: {},
        agentPay: {}
      },
      detailOrderQuery: {},
      detailOrderType: [
        {
          attrs: { column: 2, title: '基础信息' },
          list: [
            { label: '内单号', key: 'code' },
            { label: '代理商', key: 'agentname' },
            { label: '代理商价格$', key: 'agentprice' },
            { label: '支付金额$', key: 'price' },
            { label: '客户代码', key: 'appusercode' }
          ]
        },
        {
          attrs: { column: 2, title: '客户支付' },
          list: [
            { label: '支付时间', key: 'userPaypaytime' },
            { label: '经手人', key: 'userPayusername' },
            { label: '货币', key: 'userPaycurrencyname' },
            { label: '金额', key: 'userPayamount' }
          ]
        },
        {
          attrs: { column: 2, title: '代理商支付' },
          list: [
            { label: '支付时间', key: 'agentPaypaytime' },
            { label: '经手人', key: 'agentPayusername' },
            { label: '货币', key: 'agentPaycurrencyname' },
            { label: '金额', key: 'agentPayamount' }
          ]
        }
      ]
    };
  },
  created () {
    this.init()
  },
  mounted () {

    // this.PreviewPhotoList = ["http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"]
    // this.$refs.PreviewImage.clickHandler()
  },
  methods: {

    //页面初始化
    init () {
      API.StandardDoWith(API.Courier.Get({ pageSize: 1000, status: 1, type: 1 }), this, {
        success: (detail) => {
          let dict = {}
          detail.list.map(it => {
            dict[it.id] = it
          })
          this.CourierDict = dict;
        },
      })
      this.getData();
    },


    getData () {
      this.tableLoading = true
      API.StandardDoWith(API.Agent.Get(this.getQuery()), this, {
        success: (detail) => {
          this.tableData = detail;
        },
        complete: () => {
          this.tableLoading = false
        }
      })
    },

    handleAddNew () {
      this.editVisible = true;
      this.editIsNewAdd = true;
      this.form = {
        contact: "",
        mobile: "",
        address: "",
        name: "",
      }

    },



    // 编辑操作
    handleEdit (index, row) {
      this.form = JSTool.DeepClone(row)
      this.editIsNewAdd = false;
      this.editVisible = true;
    },

    handleDelete (index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          API.StandardDoWith(API.Agent.Delete({ id: row.id }), this, {
            success: (detail) => {
              this.$message.success(`成功删除渠道`);
              this.getData()
            },
          })
        })
        .catch(() => { });

    },
    saveEdit () {
      this.$refs.form.validate((valid) => {
        if (valid) {


          let net = this.editIsNewAdd ? API.Agent.Post(this.form) : API.Agent.Put(this.form)
          API.StandardDoWith(net, this, {
            success: (detail) => {
              this.editVisible = false;
              this.$message.success(`成功提交代理`);
              this.getData()
            },
          })
        } else {
          this.$message.error(`表单验证失败，无法提交`);
          return false;
        }
      });
    },

    formAddDetail () {
      if (!(this.form.courieres instanceof Array)) {
        this.form.courieres = []
      }
      this.form.courieres.push({ courierId: null })
    },
    formDeleteDetail (index) {
      this.form.courieres.splice(index, 1)
    },
    SwitchClose (item) {
      console.log(item)
      this.$set(this.tableData[item.$index], 'close', !item.row.close)
    },
    handleDetail (index, row) {
      this.detailform = null;
      this.tableDetailData = [];
      this.itemDetailTotal = 0;
      this.detailUserAccounts = [];
      this.detailQuery = {
        index: 1,
        pageSize: 10
      };
      this.detailform = {};
      this.detailform.agentid = row.id;
      this.detailform.agentname = row.name;
      this.detailVisible = true;
      this.detailQuery.id = this.detailform.agentid;
      this.getDetailData();
    },
    getDetailData () {
      this.tableDetailLoading = false;
      API.StandardDoWith(API.AgentUserData.Get(this.detailQuery), this, {
        success: (detail) => {
          this.tableDetailData = detail.list;
          this.itemDetailTotal = detail.count;
          this.detailUserAccounts = detail.accounts;
        },
        complete: () => {
          this.tableDetailLoading = false;
        }
      });
    },
    handleDetailPageChange (val) {
      this.$set(this.detailQuery, 'index', val);
      this.getDetailData();
    },
    handleDetailPageSizeChange (val) {
      this.$set(this.detailQuery, 'pageSize', val);
      this.getDetailData();
    },
    handleDetailOrder (index, row) {
      this.detailOrderForm = null;
      this.detailOrderForm = {};
      this.detailOrderForm.code = row.ordercode;
      this.detailOrderQuery.code = this.detailOrderForm.code;
      API.StandardDoWith(API.PackageDeliver.Get(this.detailOrderQuery), this, {
        success: (detail) => {
          console.log(detail);
          detail = detail.list[0];
          this.detailOrderForm.id = detail.id;
          this.detailOrderForm.agentid = detail.agentid;
          this.detailOrderForm.agentname = detail.agentname;
          this.detailOrderForm.agentprice = detail.agentprice;
          this.detailOrderForm.localagentprice = detail.localagentprice;
          this.detailOrderForm.price = detail.price;
          this.detailOrderForm.freightprice = detail.freightprice;
          this.detailOrderForm.appusercode = detail.appusercode;
          this.detailOrderForm.username = detail.userName;

          if (detail.userPay) {
            this.detailOrderForm.userPaypaytime = detail.userPay.paytime;
            this.detailOrderForm.userPayuserid = detail.userPay.userid;
            this.detailOrderForm.userPayusername = detail.userPay.username;
            this.detailOrderForm.userPaycurrencyid = detail.userPay.currencyid;
            this.detailOrderForm.userPaycurrencyname = detail.userPay.currencyname;
            this.detailOrderForm.userPayamount = detail.userPay.amount;
          }
          if (detail.agentPay) {
            this.detailOrderForm.agentPaypaytime = detail.agentPay.paytime;
            this.detailOrderForm.agentPayuserid = detail.agentPay.userid;
            this.detailOrderForm.agentPayusername = detail.agentPay.username;
            this.detailOrderForm.agentPaycurrencyid = detail.agentPay.currencyid;
            this.detailOrderForm.agentPaycurrencyname = detail.agentPay.currencyname;
            this.detailOrderForm.agentPayamount = detail.agentPay.amount;
          }
        },
        complete: () => {
          this.detailOrderVisible = true;
        }
      });
    },
    handleExport () {
      this.$confirm('是否导出Excel数据?', '提示',).then(() => {
        API.StandardDownFile(API.AgentUserDataExport({id:this.detailform.agentid}), '出货成本.xlsx')
      }).catch(err => {})
      

      // var a = document.createElement('a');
      // a.style.display = 'none'
      // a.download = '出货成本.xlsx';
      // a.href = this.$store.state.baseURL + 'api/AgentUserDataExport?id=' + this.detailform.agentid;
      // document.body.appendChild(a);
      // a.click();
      // document.body.removeChild(a);
    }
  }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
</style>
